const WebSocket = require('ws');
const express = require('express');
const cors = require('cors');
const http = require('http');
const { mockChatMessages, getAiNameForChat, formatTime } = require('./mock-data');

// 创建Express应用
const app = express();
app.use(cors());
app.use(express.json());

// 创建HTTP服务器
const server = http.createServer(app);

// 创建WebSocket服务器
const wss = new WebSocket.Server({ server });

// 存储连接的客户端
const clients = new Map();

// 处理新连接
wss.on('connection', (ws) => {
  const clientId = Date.now().toString();
  clients.set(clientId, ws);

  console.log(`Client connected: ${clientId}`);

  // 发送连接成功事件
  ws.send(JSON.stringify({
    type: 'connect',
    payload: { clientId }
  }));

  // 处理接收到的消息
  ws.on('message', (message) => {
    try {
      const data = JSON.parse(message.toString());
      console.log(`Received: ${data.type}`, data.payload);

      // 根据消息类型处理
      switch (data.type) {
        case 'join_chat':
          handleJoinChat(ws, data.payload);
          break;
        case 'send_message':
          handleSendMessage(ws, data.payload);
          break;
        case 'typing':
          handleTyping(ws, data.payload);
          break;
        default:
          console.log(`Unknown message type: ${data.type}`);
      }
    } catch (error) {
      console.error('Error processing message:', error);
    }
  });

  // 处理客户端断开连接
  ws.on('close', () => {
    clients.delete(clientId);
    console.log(`Client disconnected: ${clientId}`);
  });
});

// 处理加入聊天
function handleJoinChat(ws, payload) {
  const { chatId } = payload;
  
  // 获取模拟聊天数据
  const messages = mockChatMessages[chatId] || [];
  
  // 发送聊天历史
  setTimeout(() => {
    ws.send(JSON.stringify({
      type: 'chat_history',
      payload: {
        chatId,
        messages
      }
    }));
  }, 500);
}

// 处理发送消息
function handleSendMessage(ws, payload) {
  const { chatId, message } = payload;
  
  // 确认消息已送达
  setTimeout(() => {
    ws.send(JSON.stringify({
      type: 'message_delivered',
      payload: {
        messageId: message.id,
        chatId,
        timestamp: new Date().toISOString()
      }
    }));
    
    // 模拟AI正在输入
    setTimeout(() => {
      const aiName = getAiNameForChat(chatId);
      
      ws.send(JSON.stringify({
        type: 'typing_start',
        payload: {
          chatId,
          sender: aiName
        }
      }));
      
      // 模拟AI回复
      setTimeout(() => {
        // 停止输入状态
        ws.send(JSON.stringify({
          type: 'typing_end',
          payload: {
            chatId,
            sender: aiName
          }
        }));
        
        // 发送AI回复
        const aiResponse = {
          id: Date.now().toString() + Math.floor(Math.random() * 1000).toString(),
          type: 'system',
          sender: aiName,
          content: `我收到了您的消息: "${message.content}"`,
          time: new Date().toISOString()
        };
        
        ws.send(JSON.stringify({
          type: 'new_message',
          payload: {
            chatId,
            message: aiResponse
          }
        }));
      }, 1500);
    }, 500);
  }, 300);
}

// 处理正在输入状态
function handleTyping(ws, payload) {
  // 不需要特别处理，仅记录
  console.log(`Typing status: ${payload.isTyping ? 'started' : 'stopped'} for chat ${payload.chatId}`);
}

// 日志记录中间件
app.use((req, res, next) => {
  console.log(`${req.method} ${req.url}`);
  next();
});

// 健康检查接口
app.get('/health', (req, res) => {
  res.json({ status: 'ok', clients: clients.size });
});

// 启动服务器
const PORT = process.env.SW_PORT || 8081;
server.listen(PORT, () => {
  console.log(`WebSocket server running on port ${PORT}`);
  console.log(`WebSocket URL: ws://localhost:${PORT}`);
  console.log(`Health check: http://localhost:${PORT}/health`);
});